<script setup>
import { nextTick, reactive, ref } from "vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import config from "../../../config";
import {useUserStore} from "@/stores/user";
import { useRouter } from "vue-router";

const router = useRouter()
const total = ref(0)

const userStore = useUserStore()
const token = userStore.getBearerToken
const auths =  userStore.getAuths

const state = reactive({
  tableData: [],
  form: {}
})

const valueHtml = ref('')  // 富文本内容

state.goodsOptions = []
request.get('/goods').then(res => state.goodsOptions = res.data)
state.userOptions = []
request.get('/user').then(res => state.userOptions = res.data)


const multipleSelection = ref([])

// 批量选择
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  // 选中时计算价格
  calCart()
}

const calCart = () => {
  request.post("/cart/cal", multipleSelection.value).then(res => {
    if (res.data) {
      total.value = res.data
    }
  })
}

const confirmDelBatch = () => {
  if (!multipleSelection.value || !multipleSelection.value.length) {
    ElMessage.warning("请选择数据")
    return
  }
  const idArr = multipleSelection.value.map(v => v.id)
  request.post('/cart/del/batch', idArr).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      load()  // 刷新表格数据
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const load = () => {
  request.get('/cart/front').then(res => {
    state.tableData = res.data
    total.value = 0
  })
}
load()  // 调用 load方法拿到后台数据

const reset = () => {
  name.value = ''
  load()
}

const dialogFormVisible = ref(false)

const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ]
})
const ruleFormRef = ref()

// 新增
const handleAdd = () => {
  dialogFormVisible.value = true
  nextTick(() => {
    ruleFormRef.value.resetFields()
    state.form = {}
    valueHtml.value = ''
  })
}

// 保存
const save = () => {
  ruleFormRef.value.validate(valid => {   // valid就是校验的结果
    if (valid) {
      state.form.content = valueHtml.value  // 富文本保存内容
      request.request({
        url: '/cart',
        method: state.form.id ? 'put' : 'post',
        data: state.form
      }).then(res => {
        if (res.code === '200') {
          ElMessage.success('保存成功')
          dialogFormVisible.value = false
          load()  // 刷新表格数据
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

// 编辑
const handleEdit = (raw) => {
  dialogFormVisible.value = true
  nextTick(() => {
    ruleFormRef.value.resetFields()
    state.form = JSON.parse(JSON.stringify(raw))
    valueHtml.value = raw.content  // 富文本
  })
}

// 删除
const del = (id) => {
  request.delete('/cart/' + id).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      load()  // 刷新表格数据
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 导出接口
const exportData = () => {
  window.open(`http://${config.serverUrl}/cart/export`)
}


const handleImportSuccess = () => {
  // 刷新表格
  load()
  ElMessage.success("导入成功")
}

const handleFileUploadSuccess = (res) => {
  state.form.file = res.data
  ElMessage.success('上传成功')
}
const handleImgUploadSuccess = (res) => {
  state.form.img = res.data
  ElMessage.success('上传成功')
}

const changeNum = (row) => {
  // put更新操作
  request.put('/cart', row).then(res =>{
    calCart()
  })
}

// // 将勾选的物品计算价格，跳转到支付界面
// const submitOrder = () => {
//   request.push()
// }

// 去结算
const goToOrder = () => {
  if (!multipleSelection.value || !multipleSelection.value.length) {
    // 没勾选
    ElMessage.error("请选择商品")
    return
  }
  router.push('/front/Order?id=' + multipleSelection.value.map(value => value.id).join(","))
}

</script>

<template>
  <div>
    <div style="margin: 10px 0">
      <el-popconfirm title="您确定删除吗？" @confirm="confirmDelBatch">
        <template #reference>
          <el-button type="danger">
            <el-icon style="vertical-align: middle">
              <Remove />
            </el-icon>  <span style="vertical-align: middle"> 批量删除 </span>
          </el-button>
        </template>
      </el-popconfirm>
    </div>

    <div style="margin: 10px 0">
      <el-table :data="state.tableData" stripe border  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="编号"></el-table-column>
        
        <el-table-column label="商品图片"><template #default="scope">
          <img v-if="scope.row.goods.imgs" style="width: 70px; height: 70px" :src="scope.row.goods.imgs[0].url">
        </template></el-table-column>
        
        <el-table-column label="商品"><template #default="scope"><span v-if="scope.row.goodsId">
        {{ scope.row.goods.name }}
      </span></template></el-table-column>
        
      <el-table-column prop="num" label="商品数量">
        <template #default="scope">
          <el-input-number :min="1" v-model="scope.row.num" style="width: 120px" @change="changeNum(scope.row)"></el-input-number>
        </template>
      </el-table-column>

        <el-table-column label="商品价格"><template #default="scope">
          <span v-if="scope.row.goodsId" style="color: red; font-weight: bold; font-size: 19px">
        {{ scope.row.goods.price }}
          </span></template>
        </el-table-column>
        

        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-popconfirm title="您确定删除吗？" @confirm="del(scope.row.id)">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div style="box-shadow: 0 0 10px -2px rgba(0,0,0,0.2); padding: 10px; border-radius: 10px; text-align: right">
      总价：<span style="color: red; font-size: 26px; font-weight: lighter">{{ total }} </span>&nbsp;大米
      <div style="margin-top: 8px">
        <el-button style="background-color: mediumvioletred; color: white" @click="goToOrder">
          <el-icon><Wallet /></el-icon>&nbsp;去交米
        </el-button>
      </div>
    </div>
    
  </div>
</template>
